import React from 'react';
// 一个 JavaScript 的实用工具库
import _ from 'lodash';

function windowWidthHoc(Component) {
    class WrappedComponent extends React.Component {
        constructor(props) {
            super(props);
            
            this.getWidth = _.debounce(this.getWidth, 200);
        }

        state = {
            windowWidth : window.innerWidth
        }

        getWidth = () => {
            const windowWidth = window.innerWidth;
            this.setState({
                windowWidth
            });
        }

        componentDidMount() {
            window.addEventListener("resize", this.getWidth);
        }

        componentWillUnmount() {
            window.removeEventListener("resize", this.getWidth)
        }

        render() {
            const { windowWidth } = this.state;
            return (
              <>
                <span>窗口宽度：</span>
                    <Component
                        {...this.props}
                        windowWidth={windowWidth}
                    />
              </>
            );
        }
    }
    return WrappedComponent;
}

export default windowWidthHoc;